# -*- coding: utf-8 -*-

import os
import sys
import _winreg

import wx

import WbMainForm
import WbEditDialog

__all__ = ['opj', 'installwxgettext', 'main']

class RegCtrl(object):
    def __init__(self):
        key = _winreg.HKEY_CLASSES_ROOT
        subKey = r'*\shell'
        sam = _winreg.KEY_ALL_ACCESS
        self.Key = _winreg.OpenKey(key, subKey, 0, sam)
    
    def registe(self):
        filename = os.path.basename(sys.argv[0])
        path = os.path.normpath(os.path.abspath(filename))
        f, ext = os.path.splitext(filename)
        if ext == '.exe':
            command = '"%s" "%%1"' % path
        else:
            execute = sys.executable # "x:\Python25\python(w).exe"
            command = '"%s" "%s" "%%1"' % (execute, path)
        type = _winreg.REG_SZ
        helpmsg = _("Modify File Times with WbMFT")
        import types
        if isinstance(helpmsg, types.UnicodeType):
            helpmsg = helpmsg.encode(sys.getfilesystemencoding())
        subKeys = {
            r'WbMFT': helpmsg,
            r'WbMFT\command': command
            }
        try:
            for (sub_key, value) in subKeys.items():
                _winreg.SetValue(self.Key, sub_key, type, value)
        except:
            messages = _("Registering WbMFT to the context menu of Windows Explorer failed.")
            wx.MessageBox(messages, _("Error"), wx.OK | wx.ICON_EXCLAMATION)
            return False
        return True
    
    def unregiste(self):
        subKeys = [r'WbMFT\command', r'WbMFT']
        try:
            for sub_key in subKeys:
                _winreg.DeleteKey(self.Key, sub_key)
        except:
            messages = _("Unregistering WbMFT from the context menu of Windows Explorer failed.")
            wx.MessageBox(messages, _("Error"), wx.OK | wx.ICON_EXCLAMATION)
            return False
        return True
    
    def close(self):
        _winreg.CloseKey(self.Key)


class wxApp(wx.App):
    def Oninit(self):
        return True

class MainApp(object):
    def __init__(self, file=""):
        self.wxApp = wxApp(0)
        # Set locale for wxWidgets
        self.locale = wx.Locale(wx.LANGUAGE_DEFAULT)
        self.locale.AddCatalogLookupPathPrefix('locale')
        self.locale.AddCatalog('messages')
        # Set mainform
        if not file:
            self.frame = WbMainForm.create()
            self.fillRegeditMenu()
            self.frame.Show()
            self.wxApp.SetTopWindow(self.frame)
        else:
            self.frame = WbEditDialog.create(file=file)
            self.frame.CenterOnScreen()
            val = self.frame.ShowModal()
            if val == wx.ID_OK:
                self.frame.setFileAttrs()
            self.frame.Destroy()
        self.wxApp.MainLoop()
    
    def fillRegeditMenu(self):
        menu = self.frame.GetMenuBar().GetMenu(0)
        menu.PrependSeparator()
        unregitem = menu.Prepend(-1, _("Unregister From Windows Explorer"))
        self.frame.Bind(wx.EVT_MENU, self.OnUnregItem, unregitem)
        regitem = menu.Prepend(-1, _("Register To Windows Explorer"))
        self.frame.Bind(wx.EVT_MENU, self.OnRegItem, regitem)
    
    def OnRegItem(self, event):
        reg = RegCtrl()
        if reg.registe():
            self.frame.GetStatusBar().SetStatusText(_("Done."))
        reg.close()
    
    def OnUnregItem(self, event):
        reg = RegCtrl()
        if reg.unregiste():
            self.frame.GetStatusBar().SetStatusText(_("Done."))
        reg.close()
    
def opj(path):
    """Convert paths to the platform-specific separator"""
    st = apply(os.path.join, tuple(path.split('/')))
    # HACK: on Linux, a leading / gets lost...
    if path.startswith('/'):
        st = '/' + st
    return st

def installwxgettext():
    import wx
    import __builtin__
    __builtin__.__dict__['_'] = wx.GetTranslation

def main(file=''):
    installwxgettext()
    MainApp(file)

if __name__ == '__main__':
    main()
